package com.example.sanchuang_demo.web;

import com.example.sanchuang_demo.mapper.LoginMapper;
import com.example.sanchuang_demo.web.dto.ResponseDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/sc_demo")
@Slf4j
public class LoginController {
    @Autowired
    private LoginMapper loginMapper;



    @CrossOrigin
    @ResponseBody
    @GetMapping("/login")
    public ResponseDto<?> login(@RequestParam("userName") String userName, @RequestParam("password") String password) {
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();

        //自己系统的密码加密方式 ,这里简单示例一下MD5
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, md5Password);
        try {
            //进行验证，AuthenticationException可以catch到,但是AuthorizationException因为我们使用注解方式,是catch不到的,所以后面使用全局异常捕抓去获取
            subject.login(usernamePasswordToken);
//            UserInfo userInfo = baseMapper.selectById(username);
//            //利用shiro的Util获取sessionId
//            String sessionId = (String) subject.getSession().getId();
//            //存储用户信息
//            ShiroUtils.setSessionAttribute(SessionConst.USER_INFO_SESSION,userInfo);
//
//            System.out.println((String)ShiroUtils.getSession().getId());
//
//            userInfo.setSalt("");
//            userInfo.setPassword("");
//            Map<String,Object> data = new HashMap<>();
//            //保存key-value类型数据AUTHORIZATION，值为sessionId
//            data.put("AUTHORIZATION", sessionId);
//            data.put("userInfo",userInfo);
//            //回传给前端
//            return ResponseResult.success(data);

        } catch (AuthenticationException e) {
            e.printStackTrace();

            return new ResponseDto<>(false,"账号或密码错误！",null);
        } catch (AuthorizationException e) {
            e.printStackTrace();

            return new ResponseDto<>(false,"没有权限",null);
        }
        return new ResponseDto<>(true,"login success",null);

    }



}